import axios from "axios";
import Qs from 'qs'
import { Loading } from 'element-ui';
import { MessageBox } from 'element-ui';
import {clearTokenAndStore} from "../common/auth";
let env=process.env.NODE_ENV;
const axiosUtil=axios.create({
  transformRequest: (data, headers) => {
    if (!data) {
      data = {}
    }
    return JSON.stringify(data)
  },
  baseURL:env==='production'?'http://127.0.0.1/ai-face-system/ai_face/ai-face-attendance':'http://127.0.0.1/ai-face-system/ai_face/ai-face-attendance',
  timeout:100000
});
    // 拦截request,设置全局请求为ajax请求

axiosUtil.interceptors.request.use((config) => {
  let token=sessionStorage.getItem("token");
  if (token == null || token == undefined || typeof (token) == 'undefined' || token === '' || token == "undefined") {
    token=""
  }
  config.headers['token'] = token;
      return config
    })

// 拦截响应response，并做一些错误处理
axiosUtil.interceptors.response.use((response) => {
      const data = response.data
      if (data.code!=='200'){
        // 若不是正确的返回code，且已经登录，就抛出错误
        switch (data.code) {
          case '500':
            data.message="服务器内部异常,具体原因是:"+data.message;
            break;
          case '403':
            clearTokenAndStore();
            data.message="用户信息已经过期,请重新登录";
            break;
          default:
            data.message="请求失败,请稍后重试";
            break;
        }
        return Promise.reject(data);
      }
// 根据返回的code值来做不同的处理（和后端约定）
//       data.description=data.msg;
      if (data.token!==''){
        sessionStorage.setItem("token",data.token);
      }
      response=data.data;

      return response
    }, (err) => { // 这里是返回状态码不为200时候的错误处理
      if (err && err.response) {
        switch (err.response.status) {
          case 400:
            err.message = '请求错误'
            break

          case 401:
            err.message = '未授权，请登录'
            break

          case 403:
            err.message = '登录信息已过期，请重新登录';
            sessionStorage.clear()
            break

          case 404:
            err.message = `请求地址出错: ${err.response.config.url}`
            break

          case 408:
            err.message = '请求超时'
            break

          case 500:
            err.message = '服务器内部错误'
            break

          case 501:
            err.message = '服务未实现'
            break

          case 502:
            err.message = '网关错误'
            break

          case 503:
            err.message = '服务不可用'
            break

          case 504:
            err.message = '网关超时'
            break

          case 505:
            err.message = 'HTTP版本不受支持'
            break

          default:
            err.message="请求失败";
            break;
        }
      }
      return Promise.reject(err)
    })
axiosUtil.$ajax=(url, {isErrorTip = true, errContent, disableName, renDisName, isLoading = true, noRepeatId, axiosCf = {}} = {})=>{
  return new Promise((resolve, reject) => {
    let loadingInstance=Loading.service({fullscreen:true})
    axiosCf.headers = {
      'Content-Type': 'application/json;charset=UTF-8'
    }
    axiosCf.url = url
    this.a(axiosCf).then(data => {
      if (loadingInstance){
        loadingInstance.close()
      }
      resolve(data)
    }).catch(result => {
      if (loadingInstance){
        loadingInstance.close()
      }
      MessageBox({title:'错误',message:result.message,type:'error'});
      reject(result)
    })
  })
}
  axiosUtil.$ajaxGet=(url, data, config)=>{
    config = config || {}
    if (!config.axiosCf) {
      config.axiosCf = {}
    }
    data = data || {}
    data = Qs.stringify(data)
    if (data) {
      url = url + '?' + data
    }
    config.axiosCf.method = 'get'
    return this.a.$ajax(url, config)
  }
  axiosUtil.$ajaxpost=(url, data, config)=>{
    config = config || {}
    if (!config.axiosCf) {
      config.axiosCf = {}
    }
    config.axiosCf.data = data
    config.axiosCf.method = 'post'
    return this.a.$ajax(url, config)
  }

  axiosUtil.$ajaxDelete=(url, data, config)=>{
    config = config || {}
    if (!config.axiosCf) {
      config.axiosCf = {}
    }
    config.axiosCf.data = data
    config.axiosCf.method = 'delete'
    return this.a.$ajax(url, config)
  }
  axiosUtil.$ajaxPut=(url, data, config)=>{
    config = config || {}
    if (!config.axiosCf) {
      config.axiosCf = {}
    }
    config.axiosCf.data = data
    config.axiosCf.method = 'put'
    return this.a.$ajax(url, config)
  }

export default  axiosUtil
